/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.lojapi.controle;

import br.com.lojapi.bean.Perfil;
import br.com.lojapi.bean.Usuario;
import br.com.lojapi.dao.PerfilDAO;
import br.com.lojapi.dao.PerfilDAOImp;
import br.com.lojapi.dao.UsuarioDAO;
import br.com.lojapi.dao.UsuarioDAOImp;
import br.com.lojapi.enviaemail.EnviaEmail;
import java.io.IOException;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Aluno
 */
@WebServlet(name = "UsuarioServlet", urlPatterns = {"/usuario_do"})
public class UsuarioServlet extends HttpServlet {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private RequestDispatcher rd;
    private UsuarioDAO usuarioDAO;
    private Usuario usuario;

    protected void processRequest() throws ServletException, IOException {
        String cmd = request.getParameter("cmd");
        switch (cmd) {
            case "salvaUsuario":
                salvaUsuario();
                break;
            case "cadUsuario":
                carregaCombo();
                break;

            case "logar":
                logar();
                break;
            case "sair":
                logof();
                break;
        }
        rd.forward(request, response);
    }

    private void salvaUsuario() {
        carregaUsuario();
        usuarioDAO = new UsuarioDAOImp();
        try {
            usuarioDAO.salvar(usuario);
            //manda e-mail com dados do usuário
            EnviaEmail enviaEmail = new EnviaEmail();
            try {
                enviaEmail.enviaEmailSimples(usuario);
                request.setAttribute("msg", "Usuário salva com sucesso!");
            } catch (MessagingException me) {
                //montar mensagem de erro para email
                System.out.println("Erro ao enviar e-mail " + me.getMessage());
            }
            rd = request.getRequestDispatcher("index.jsp");
        } catch (Exception e) {
            System.out.println("erro ao salvar usuário " + e.getMessage());
        }
    }

    private void carregaCombo() {
        PerfilDAO perfilDAO = new PerfilDAOImp();
        try {
            List perfis = perfilDAO.listar();
            request.setAttribute("perfis", perfis);
            rd = request.getRequestDispatcher("cadUsuario.jsp");
        } catch (Exception e) {
            System.out.println("erro ao carregar combo " + e.getMessage());
        }
    }

    private void carregaUsuario() {

        usuario = new Usuario();
        Perfil perfil = new Perfil();

        String id = request.getParameter("id");
        if (id != null) {
            usuario.setId(Integer.parseInt(id));
        }
        usuario.setNome(request.getParameter("nome"));
        usuario.setLogin(request.getParameter("login"));
        usuario.setEmail(request.getParameter("email"));
        String senha = request.getParameter("senha");
        if (senha == null) {
            int x = (int) (Math.random() * 10000);
            senha = Integer.toString(x);
            usuario.setSenha(senha);
        } else {
            usuario.setSenha(request.getParameter("senha"));
        }

        perfil.setId(Integer.parseInt(request.getParameter("idPerfil")));
        usuario.setPerfil(perfil);
    }

    private void logar() {
        usuarioDAO = new UsuarioDAOImp();
        try {
            String login = request.getParameter("login");
            String senha = request.getParameter("senha");
            usuario = usuarioDAO.logar(login, senha);
            if (usuario.isLogado()) {
                HttpSession session = request.getSession(true);
                session.setAttribute("usuario", usuario);
                rd = request.getRequestDispatcher("index.jsp");
            } else {
                request.setAttribute("mens", "Login ou Senha incorretos!");
                rd = request.getRequestDispatcher("sistema.jsp");
            }
        } catch (Exception e) {
        }
    }

    private void logof() {
        HttpSession session = request.getSession(true);
        session.removeAttribute("usuario");
        rd = request.getRequestDispatcher("index.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.request = request;
        this.response = response;
        processRequest();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.request = request;
        this.response = response;
        processRequest();
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
